/*
Copyright 2010 Darryl Parker

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

file: wpl-amazon-extension\amazonscript.js

*/

// takes the result of the RPC call and inserts appropriate text.
function onBook(book) {

  if (book) {

     var notice;

     if (book.found) {

        notice = document.createElement("a");
        notice.setAttribute('title', isbn);
        notice.setAttribute('href', 'http://wpl-pac.winnipeg.ca/ipac20/ipac.jsp?index=ISBNEX&term=' + isbn);
        notice.setAttribute('style','color:red\;' + 'background-color:#FFFF99\;' + 'font-size:12px');
        
     }
     else {

        notice = document.createElement("span");
        notice.setAttribute('style','color:LightGrey\;' + 'font-size:12px');

     }

      var message = document.createTextNode(book.message);

      notice.appendChild(message);

      var origTitle = document.evaluate("//span[@id='btAsinTitle']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
      var div = origTitle.parentNode;
      var title = origTitle.firstChild.nodeValue;

      var newTitle = document.createElement('b');
      newTitle.setAttribute('class','sans');

      var titleText = document.createTextNode(title);
      newTitle.appendChild(titleText);

      var br = document.createElement('br');

      div.insertBefore(newTitle, origTitle);
      div.insertBefore(br, origTitle);
      div.insertBefore(notice, origTitle);
      div.removeChild(origTitle);

  }

}  //onBook

// attempt to pull the ISBN out of the current URL
// runs on every page matching the manifest's directive
try
{
  isbn = window.location.href.match(/\/(\d{7,9}[\d|X])\//)[1];
  if (isbn) {
    chrome.extension.sendRequest({'action' : 'checkAvailability', 'isbn' : isbn}, onBook);
  }
}
catch (e)
{
  return;
}